/**
 * 易驰护运 - Wallet
 * http://menger.me
 * 钱包
 * @桓桓
 */

'use strict';

import React from 'react'
import { StyleSheet, Text, ScrollView, TouchableOpacity, ImageBackground, View, Keyboard} from 'react-native';
import {
    IconFont,
    ListView,
    VerticalLine,
    HorizontalLine,
    BannerComponent,
    HotNewsComponent,
    HomeResourceItem,
    ListHeaderLoading,
} from '../../components';
import {inject, observer} from 'mobx-react';
import WalletItem from '../../components/customer/Item/WalletItem';

@inject('loginStore')
@observer
export default class Wallet extends React.Component {

    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.state = {
            loading: true,
            dataSources: [],
            statistic: [],
            memberBalance: '',
            year: Moment(new Date()).format('YYYY'),
            month: Moment(new Date()).format('MM'),
        }
        this.page = 1;
        this.limit = 10;
    }

    componentDidMount() {
        this._requestDataSources();
    }

    componentWillUnmount() {
        this.timerArray = [this.stopLoadingTimer];
        ClearTimeOut(this.timerArray);
    }

    _requestDataSources = async () => {
        let { dataSources, year, month } = this.state;
        let url = ServicesApi.PERSONAL_CENTER_MY_BALANCE;
        let data = {
            year,
            month,
            page: this.page,
            limit: this.limit,
        };
        try {
            const result = await Services.post(url, data);
            let dataSourceTemp = dataSources.slice();
            let dataList = [];
            if (result.code === StatusCode.SUCCESS_CODE) {
                dataList = result.data.finance_list.dataList || [];
                if (parseInt(data.page) === 1) {
                    dataSourceTemp = dataList
                } else {
                    if (dataList.length !== 0) {
                        dataSourceTemp = dataSourceTemp.concat(dataList);
                    }
                }
            }
            this.setState({ 
                dataSources: dataSourceTemp,
                statistic: result.data.statistic,
                memberBalance: result.data.$member_balance,
            });
            this._onStopLoading(dataList.length < this.limit);
        } catch (error) {
            this._onStopLoading(true);
        }
    };

    // 下拉刷新
    _onRefresh = () => {
        this.page = 1;
        this._requestDataSources();
    };

    // 结束加载
    _onStopLoading = (status = true) => {
        this.stopLoadingTimer = setTimeout(() => this.setState({ loading: false, ready: true }), 500);
        this._listRef && this._listRef.stopRefresh();
        this._listRef && this._listRef.stopEndReached({ allLoad: status });
    };

    // 上拉加载
    _onEndReached = () => {
        this.page++;
        this._requestDataSources();
    }

    // 定义 refs
    _captureRef = (v) => {
        this._listRef = v
    };

    // 生成 Key
    _keyExtractor = (item, index) => {
        return `item_${index}`
    };

    // 时间选择
    showActionPicker = () => {
        Keyboard.dismiss();
        let params = {
            onPress: (value) => this.setState({
                year: value.year,
                month: value.month,
            }, () => this._onRefresh()),
            option: {
                panGestureEnabled: false,
            }
        }
        ActionManager.showWheelDayMonth(params);
    };

    _renderItem = ({item, index}) => {
        return (
            <WalletItem
                item={item}
                {...this.props}
            />
        );
    };

    renderListHeaderComponent = (statistic, memberBalance) => {
        let {year, month} = this.state;
        return (
            <View style={styles.header}>
                <ImageBackground
                    resizeMode={'cover'}
                    style={styles.headerBackground}
                    source={Images.img_wallet_bg}
                >
                    <Text style={styles.headerTitle}>我的余额 (元)</Text>
                    <Text style={styles.headerPrice} numberOfLines={1}>{memberBalance}</Text>
                    <View style={styles.headerBtnBox}>
                        <Button
                            style={styles.headerBtn}
                            title={'充值'}
                            titleStyle={styles.headerBtnTitle}
                            resizeMode={'cover'}
                            backgroundImage={Images.img_btn_bg1}
                            onPress={() => RouterHelper.navigate('', 'Recharge', {onRefresh: () => this._onRefresh()})}
                        />
                        <Button
                            style={styles.headerBtn}
                            title={'提现'}
                            titleStyle={styles.headerBtnTitle}
                            resizeMode={'cover'}
                            backgroundImage={Images.img_btn_bg1}
                            onPress={() => RouterHelper.navigate('', 'Withdraw', {onRefresh: () => this._onRefresh()})}
                        />
                    </View>
                </ImageBackground>
                <View style={styles.center}>
                    <View style={styles.centerBall}><View style={styles.centerBallCenter}/></View>
                    <Text style={styles.centerText} numberOfLines={1}>收支记录</Text>
                </View>
                <View style={styles.nav}>
                    <Text style={styles.navLeft} numberOfLines={1} onPress={() => this.showActionPicker()}>{year}年{month}月></Text>
                    <View style={styles.navRight}>
                        <Text style={[styles.navRightText, {color: '#00BFCC'}]} numberOfLines={1}>收入：￥{statistic.member_income}</Text>
                        <Text style={[styles.navRightText, {color: '#CC0000'}]} numberOfLines={1}>支出：￥{statistic.member_pay}</Text>
                    </View>
                </View>
            </View>
        )
    }

    ItemSeparatorComponent = () => {
        return <View style={{height: Predefine.minPixel, backgroundColor: '#f2f2f2', marginHorizontal: 15}}></View>
    }

    render() {
        let {dataSources, statistic, memberBalance} = this.state;
        return (
            <PageContainer style={styles.container}>
                <NavigationBar
                    // title={'我的钱包'}
                    style={[styles.navigationBarStyle]}
                />
                <ListView
                    data={dataSources}
                    ref={this._captureRef}
                    extraData={this.state}
                    style={styles.listContent}
                    onRefresh={this._onRefresh}
                    renderItem={this._renderItem}
                    keyExtractor={this._keyExtractor}
                    onEndReached={this._onEndReached}
                    ItemSeparatorComponent={this.ItemSeparatorComponent}
                    ListHeaderComponent={() => this.renderListHeaderComponent(statistic, memberBalance)}
                />
            </PageContainer>
        );
    }
}

const DominantColor = '#00BFCC';
const styles = StyleSheet.create({
    container: {
        backgroundColor: '#F0F0F0'
    },
    navigationBarStyle: {
        zIndex: 1,
        marginBottom: -NAV_BAR_HEIGHT,
        backgroundColor: 'transparent',
        borderBottomWidth: 0,
    },
    // 上面的部分
    headerBackground: {
        width: SCREEN_WIDTH,
        height: SCREEN_WIDTH * (770/1125),
        paddingTop: 50,
        alignItems: 'center',
        justifyContent: 'center',
    },
    headerTitle: {
        fontSize: 12,
        color: '#fff',
    },
    headerPrice: {
        fontSize: 40,
        color: '#fff',
        marginTop: 10,
        marginBottom: 30,
    },
    headerBtnBox: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        width: SCREEN_WIDTH - 100,
    },
    headerBtn: {
        width: SCREEN_WIDTH / 2 - 80,
        height: 36,
        borderRadius: 18,
        paddingVertical: 0,
        backgroundColor: 'transparent',
        borderWidth: Predefine.minPixel,
        borderColor: '#fff',
    },
    // 中间部分
    center: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 40,
        paddingHorizontal: 15,
    },
    centerBall: {
        width: 12,
        height: 12,
        borderRadius: 6,
        backgroundColor: DominantColor,
        marginRight: 6,
        alignItems: 'center',
        justifyContent: 'center',
    },
    centerBallCenter: {
        height: 6,
        width: 6,
        borderRadius: 3,
        backgroundColor: '#F0F0F0',
    },
    centerText: {
        color: '#333',
        fontSize: 13,
        fontWeight: 'bold',
    },
    // nav
    nav: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingHorizontal: 15,
        height: 50,
        backgroundColor: '#F7F7F7',
    },
    navLeft: {
        fontSize: 12,
        color: '#666',
    },
    navRight: {
        flex: 1,
    },
    navRightText: {
        fontSize: 12,
        textAlign: 'right',
    },
});